#!/usr/bin/env ruby

# code modified from http://rubyforge.org/docman/view.php/85/107/instiki_service_tutorial.txt
# chris . hulbert at gmail . coms

require 'optparse'
require 'win32/service'
include Win32

# default options
OPTIONS = {
  :win32install => false,
  :win32uninstall => false,
  :win32start => false,
  :win32stop => false,
  :win32servicename => 'BackgrounDRb'
}
DAEMON = "#{File.expand_path(File.dirname(__FILE__) + "/../../")}/script/backgroundrb/win32daemon"

ARGV.options do |o|
  script_name = File.basename($0)
  
  o.set_summary_indent('  ')
  o.banner =    "Usage: #{script_name} [options]"
  o.define_head "Working with BackgrounDRb services"
  o.separator   ""
  
  o.on("-i", "--win32-service-install",
       "Install as a win32 service") { |OPTIONS[:win32install]| }
  o.on("-d", "--win32-service-delete",
       "Delete the win32 service") { |OPTIONS[:win32uninstall]| }
  o.on("-s", "--win32-service-start",
       "Starts the win32 service") { |OPTIONS[:win32start]| }
  o.on("-x", "--win32-service-stop",
       "Stops the win32 service") { |OPTIONS[:win32stop]| }
  o.on("-n", "--win32-service-name [name]", String,
       "An optional name for the win32 service",
       "Default: #{OPTIONS[:win32servicename]}")   { |OPTIONS[:win32servicename]| }
  
  o.separator ""

  o.on_tail("-h", "--help", "Show this help message.") { puts o; exit }
  
  o.parse!
end

# if they want to install/start/stop it as a win32 service, do that now
if OPTIONS[:win32install]
  puts "Installing as a win32 service, ruby must be installed at c:\\ruby\\bin\\ruby.exe\n"
  s = Service.new
  s.create_service{ |s|
    s.service_name = OPTIONS[:win32servicename]
    s.display_name = OPTIONS[:win32servicename]
    s.service_description = 'http://rubyforge.org/projects/backgroundrb/'
    s.binary_path_name = "C:\\ruby\\bin\\ruby " + DAEMON
    s.start_type = Service::AUTO_START
  }
  s.close
  puts "Done! Do start->run 'services.msc' to have a look.\n"
  puts "Hint: It'll auto-start at boot-up.\n"
end
if OPTIONS[:win32uninstall]
  Service.delete OPTIONS[:win32servicename]
  puts "Service is marked for deletion, and will be removed either now or next reboot.\n"
  exit
end
if OPTIONS[:win32start]
  puts 'Service starting...'
  Service.start OPTIONS[:win32servicename]
  exit
end
if OPTIONS[:win32stop]
  puts 'Service stopping...'
  Service.stop OPTIONS[:win32servicename]
end
 